// pages/zstz/selfPkResult/selfPkResult.js
const app = getApp().globalData;
let userScore;
var md5 = require("../../../utils/md5.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: '', //用户信息
    typeId: '',
    typeName: '',
    singleAnswerNumber: '', //每次答题数量
    singleAnswerTime: '', //单次答题时间
    singleScore: 0, //单题分值
    questionBank: [], //题目
    countDownNum: '', //倒计时
    circleMove: 'circleMove', //动效慢慢出现
    rotateLeft: 'rotateLeft',
    rotateRight: 'rotateRight',
    titleMove: 'titleMove',
    titleNoMove: 'titleNoMove',
    answersMove: 'answersMove',
    title: '', //题目
    index: 0, //第n题
    answer: [], //选项
    alreadyClick: false, //已经点击过的就不能再点击
    startTime: '', //每题开始答题时间
    correctId: '', //本次正确的答案
    correctClass: '', //正确答案的状态显示
    clickId: '', //点击答案的下标
    selfClass: '', //选中答案对错状态显示
    sumScore: 0, //总得分
    timer: '', //定时器名
    timers: '', //3秒间隔定时器
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getQuestionBank(options.typeId, options.singleAnswerNumber); //根据分类id获取题目
    this.setData({
      userInfo: wx.getStorageSync('userInfo'),
      typeId: options.typeId,
      typeName: options.typeName,
      singleAnswerNumber: options.singleAnswerNumber,
      singleAnswerTime: options.singleAnswerTime,
      singleScore: options.singleScore,
    });
    wx.setNavigationBarTitle({ //动态修改标题
      title: options.typeName
    })
  },

  //根据分类id获取题目
  getQuestionBank: function (typeId, singleAnswerNumber) {
    let that = this;
    var datetime = new Date().Format('yyyy-MM-dd hh:mm:ss');
    var token = md5.md5("[typeId=" + typeId + "][singleAnswerNumber=" + singleAnswerNumber + "][date=" + datetime + "]zs0dj4jc8dwtz").toLowerCase();
    wx.request({
      url: 'https://zstz.chaoxing.com/external/interface/wx/getQuestionBank?typeId=' + typeId + '&token=' + token + '&singleAnswerNumber=' + singleAnswerNumber,
      success: function (res) {
        if (res.data.code == 0) {
          that.setData({
            questionBank: res.data.data
          })
          that.getQ(res.data.data[0]); //从第一题开始
        }
      },
      fail: function () {
        wx.showToast({ //弹窗
          title: '根据分类id获取题库异常！',
          icon: 'none'
        })
      }
    })
  },

  //请求下一题的逻辑
  getQ(questionBank) {
    let that = this;
    that.setData({
      countDownNum: Number(that.data.singleAnswerTime) + 1, //倒计时初始值
      circleMove: 'circleMove', //动效慢慢出现
      rotateLeft: 'rotateLeft',
      rotateRight: 'rotateRight',
      titleMove: 'titleMove',
      titleNoMove: 'titleNoMove',
      answersMove: 'answersMove',
      title: questionBank.qusetion, //题目,选项
      index: that.data.index + 1,
      answer: [questionBank.optionA, questionBank.optionB, questionBank.optionC, questionBank.optionD],
      startTime: new Date(),
    });
    that.countDown(); //倒计时
  },

  //倒计时
  countDown: function () {
    let that = this;
    that.data.timer = setInterval(function () {
      that.setData({ //1秒秒减少
        alreadyClick: false,
        countDownNum: --that.data.countDownNum
      });
      if (that.data.countDownNum == 0) {
        clearInterval(that.data.timer); //清空定时器
        //1.显示正确答案
        that.setData({
          alreadyClick: true, //不能点击
          correctId: that.data.questionBank[that.data.index - 1].rightOption,
          correctClass: 'true',
        });
        //2.统计用户得分信息
        that.userScore(0, '倒计时');
        //3.1秒后清除样式,再1秒后请求
        setTimeout(function () {
          that.setData({
            correctId: '', //清除正确答案样式
            correctClass: '',
            titleMove: '',
            titleNoMove: '',
            answersMove: '',
            circleMove: '', //清除倒计时
            rotateLeft: '',
            rotateRight: '',
          })
          if (that.data.index == that.data.singleAnswerNumber) { //全部答完,挑转到结束页
            that.endAnswer(userScore);
          } else {
            setTimeout(function () {
              that.getQ(that.data.questionBank[that.data.index]); //获取下一题
            }, 1000);
          }
        }, 1000);
      }
    }, 1000)
  },

  //点击选中答案
  clickAnswer: function (event) {
    let that = this;
    if (!that.data.alreadyClick) { //防止多次点击
      that.setData({
        alreadyClick: true
      });
      clearInterval(that.data.timer); //清空定时器
      let index = event.currentTarget.dataset.index; //点击的选项
      let questionBank = that.data.questionBank[that.data.index - 1]; //当前题目
      let score = 0; //此题得分
      //1.显示答案
      if (index == questionBank.rightOption) { //答对
        score = that.data.singleScore == 0 ? (200 - (new Date() - that.data.startTime) / 1000 * 10).toFixed() : that.data.singleScore; //得分算法
        score = score < 0 ? 50 : score;
        that.setData({
          clickId: index,
          selfClass: 'true left',
          rotateLeft: '', //清空动效倒计时
          rotateRight: '',
          sumScore: Number(that.data.sumScore) + Number(score), //此次答题得分之和
        });
      } else { //答错
        that.setData({
          clickId: index,
          selfClass: 'false left',
          correctId: questionBank.rightOption, //显示正确答案
          correctClass: 'true',
          rotateLeft: '', //清空动效倒计时
          rotateRight: '',
        });
      }
      //2.统计用户得分信息
      that.userScore(score, '点击');
      //3.1秒后清除样式,再1秒后请求下一题
      that.data.timers = setTimeout(() => {
        that.setData({
          clickId: '', //清空答案
          selfClass: '',
          correctId: '',
          correctClass: '',
          titleMove: '', //清空题目
          titleNoMove: '',
          answersMove: '',
          circleMove: '', //清空倒计时
        })
        if (that.data.index == that.data.singleAnswerNumber) { //全部答完,挑转到结束页
          that.endAnswer(userScore);
        } else {
          setTimeout(function () {
            that.getQ(that.data.questionBank[that.data.index]); //获取下一题
          }, 1000);
        }
      }, 1000)
    }
  },

  //统计用户得分信息
  userScore: function (score, version) {
    let that = this;
    userScore.push({
      fid: app.fid,
      unitName: app.site.name,
      typeId: that.data.typeId,
      typeName: that.data.typeName,
      wxUserId: wx.getStorageSync('openid'),
      nickName: wx.getStorageSync('userInfo').nickName,
      numbers: wx.getStorageSync('phone'),
      avatarUrl: wx.getStorageSync('userInfo').avatarUrl,
      pk_pattern: "线上竞答",
      score_time: new Date().Format('yyyy-MM-dd hh:mm:ss'),
      score: score,
      version: version,
      createdTime: new Date(),
      lastUpdatedTime: new Date()
    });
  },

  //答题结束
  endAnswer: function (userScore) {
    let that = this;
    clearInterval(that.data.timer); //清空定时器
    wx.redirectTo({ //挑转到结束页
      url: '../selfPkResult/selfPkResult?typeId=' + that.data.typeId + '&typeName=' + that.data.typeName + '&sumScore=' + that.data.sumScore
    })
    if (userScore.length >= that.data.singleAnswerNumber) {
      userScore.splice(0, userScore.length - that.data.singleAnswerNumber);
      that.saveScore(userScore);
    }
  },

  //保存用户得分信息
  saveScore: function (userScore) {
    var userScores =  JSON.stringify(userScore);
    var datetime = new Date().Format('yyyy-MM-dd hh:mm:ss');
    var token = md5.md5("[userScore="+ userScores +"][date=" + datetime + "]zs0dj4jc8dwtz").toLowerCase();
    wx.request({
      url: 'https://zstz.chaoxing.com/external/interface/wx/saveScore',
      data: {
        token: token,
        userScore: userScores
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: function (res) {
        console.log("res", res);
      },
      fail: function () {
        wx.showToast({ //弹窗
          title: '保存用户得分信息异常！',
          icon: 'none'
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    clearInterval(this.data.timer); //清空定时器
    userScore = []; //用户得分信息
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(this.data.timer); //清空定时器
    userScore = []; //用户得分信息
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})